package com.xfusion.chatglm.data.domain.openai.service.rule.impl;

import com.xfusion.chatglm.data.domain.openai.annotation.LogicStrategy;
import com.xfusion.chatglm.data.domain.openai.model.aggregates.ChatProcessAggregate;
import com.xfusion.chatglm.data.domain.openai.model.entity.RuleLogicEntity;
import com.xfusion.chatglm.data.domain.openai.model.entity.UserAccountQuotaEntity;
import com.xfusion.chatglm.data.domain.openai.model.valobj.LogicCheckTypeVO;
import com.xfusion.chatglm.data.domain.openai.repository.IOpenAiRepository;
import com.xfusion.chatglm.data.domain.openai.service.rule.ILogicFilter;
import com.xfusion.chatglm.data.domain.openai.service.rule.factory.DefaultLogicFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 用户额度扣减规则处理
 */
@Slf4j
@Component//将此类标记为Spring框架中的一个组件，允许在Spring应用上下文中进行自动扫描、注册和依赖注入
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.USER_QUOTA)
public class UserQuotaFilter implements ILogicFilter<UserAccountQuotaEntity> {
    @Resource
    private IOpenAiRepository repository;//仓储服务，与数据库和redis交互
    @Override
    public RuleLogicEntity<ChatProcessAggregate> filter(ChatProcessAggregate chatProcessAggregate, UserAccountQuotaEntity data) throws Exception {
        if (data.getSurplusQuota()>0){
            //扣减账户额度，个人账户，无资源竞争，可以直接扣减数据库，如果想效率更高，可以用redis
            int updateCount = repository.subAccountQuota(data.getOpenid());
            if (0!=updateCount){//如果扣减成功
                return RuleLogicEntity.<ChatProcessAggregate>builder().type(LogicCheckTypeVO.SUCCESS).data(chatProcessAggregate).build();
            }
            return RuleLogicEntity.<ChatProcessAggregate>builder().info("个人账户，总额度【" + data.getTotalQuota() + "】次，已耗尽！").type(LogicCheckTypeVO.REFUSE).data(chatProcessAggregate).build();
        }
        return RuleLogicEntity.<ChatProcessAggregate>builder().info("个人账户，总额度【" + data.getTotalQuota() + "】次，已耗尽！").type(LogicCheckTypeVO.REFUSE).data(chatProcessAggregate).build();
    }
}
